(async function () {
  const express = require("express");
  const cookieParser = require("cookie-parser");
  const session = require("express-session");
  const staticRouter = require("./routers/staticRouter");
  const urlRouter = require("./routers/urlRouter");
  const db = require("./mangoosedb/db/db");
  const app = express();
  const MongoStore = require("connect-mongo")(session);
  try {
    await db;
    console.log("数据库连接成功");
    app.use(express.urlencoded({ extended: true }));
    app.use(express.static("public"));
    app.use(cookieParser());
    app.use(
      session({
        name: "userid", //设置cookie的键，默认值是：connect.sid
        secret: "atguigu", //参与加密的字符串（又称签名）
        saveUninitialized: false, //是否在存储内容之前创建会话
        resave: true, //是否在每次请求时，强制重新保存session，即使他们没有变化
        store: new MongoStore({
          url: "mongodb://localhost:27017/sessions_container",
          touchAfter: 24 * 3600, //修改频率（例：//在24小时之内只更新一次）
        }),
        cookie: {
          httpOnly: true, // 开启后前端无法通过 JS 操作cookie
          maxAge: 1000 * 30, // 设置cookie的过期时间
        },
      })
    );
    app.use(urlRouter);
    app.use(staticRouter);
    app.listen(5000, (err) => {
      if (err) console.log("服务器启动失败");
      console.log("服务器启动成功");
    });
  } catch (err) {
    console.log("数据库连接失败", err);
  }
})();
